package com.sky.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.apache.ibatis.annotations.Options;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    public  String URL = "https://api.map.baidu.com/directionlite/v1/driving?";
    private  String AddURL="https://api.map.baidu.com/geocoding/v3/?";
    public  String AK = "zOZVPQAV0hB2UiQRGcbMuHpOAVmuAo5i";
    @Value("${sky.shop.address}")
    private String shopAddress;
    /**
     * 提交订单
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //数据校验（地址为空，购物车为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //获取购物车数据
        List<ShoppingCart> list = shoppingCartMapper.showShoppingCart(BaseContext.getCurrentId());
        if (list == null || list.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //获取当前地理位置坐标
        String sadd = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
//        https://api.map.baidu.com/geocoding/v3/?address=北京市海淀区上地十街10号&output=json&ak=您的ak&callback=showLocation
        String s1 = HttpClientUtil.doGet(AddURL + "address=" + sadd + "&output=json&ak=" + AK, null);
        String s2 = HttpClientUtil.doGet(AddURL + "address=" + shopAddress + "&output=json&ak=" + AK, null);
        JSONObject jsonObjectAdd1 = JSONObject.parseObject(s1);
        JSONObject jsonObjectAdd2 = JSONObject.parseObject(s2);
        JSONObject jsonObjectAdd3 = (JSONObject) jsonObjectAdd1.get("result");
        JSONObject jsonObjectAdd4 = (JSONObject) jsonObjectAdd2.get("result");
        JSONObject jsonObjectAdd5 = (JSONObject) jsonObjectAdd3.get("location");
        JSONObject jsonObjectAdd6 = (JSONObject) jsonObjectAdd4.get("location");
        Double lat1 = jsonObjectAdd5.getDouble("lat");
        Double lng1 = jsonObjectAdd5.getDouble("lng");
        Double lat2 = jsonObjectAdd6.getDouble("lat");
        Double lng2 = jsonObjectAdd6.getDouble("lng");
        //数据校验，如果距离超过5km，提示不能下单
        String url = URL + "origin="+lat1+","+lng1+"&destination="+lat2+","+lng2+"&ak=" + AK;
        //调用百度地图api
        String s = HttpClientUtil.doGet(url, null);
        JSONObject jsonObject = JSONObject.parseObject(s);
        JSONObject jsonObject1 = (JSONObject) jsonObject.get("result");
        JSONArray jsonArray = jsonObject1.getJSONArray("routes");
        JSONObject jsonObject2 = jsonArray.getJSONObject(0);
        Integer distance = jsonObject2.getIntValue("distance");
        //判断距离是否超过5km
        if (distance > 5000){
            throw new ShoppingCartBusinessException(MessageConstant.DISTANCE_TOO_LONG);
        }

        //构造订单对象，将订单信息保存到数据库订单表中
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(BaseContext.getCurrentId());
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());
        ordersMapper.insert(order);
        //构造订单明细对象，将订单明细信息保存到数据库订单明细表中
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetails);
        //清空购物车
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());
        //构造订单VO对象，将订单信息返回给前端
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
//        BeanUtils.copyProperties(order,orderSubmitVO);
        orderSubmitVO.setId(order.getId());
        orderSubmitVO.setOrderNumber(order.getNumber());
        orderSubmitVO.setOrderAmount(order.getAmount());
        orderSubmitVO.setOrderTime(order.getOrderTime());
        return orderSubmitVO;
    }

    /**
     * 历史订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        //添加userId
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //查询历史订单
        List<OrderVO> ordersList = ordersMapper.historyOrders(ordersPageQueryDTO);
        //遍历订单列表，查询订单明细
        ordersList.forEach(orderVO -> {
            orderVO.setOrderDetailList(orderDetailMapper.selectByOrderId(orderVO.getId()));
        });
        Page<OrderVO> page = (Page<OrderVO>) ordersList;
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancel(Long id, OrdersCancelDTO ordersCancelDTO) {
        //查询订单
        Orders orders = ordersMapper.getById(id);
        if (orders == null){
            throw new ShoppingCartBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (orders.getStatus() != Orders.PENDING_PAYMENT){
            throw new ShoppingCartBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        ordersMapper.updateStatus(id,Orders.CANCELLED,LocalDateTime.now(),ordersCancelDTO.getCancelReason());
    }

    /**
     * 订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetailGetById(Long id) {
       List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(id);
       if (orderDetailList == null || orderDetailList.size() == 0){
           throw new ShoppingCartBusinessException(MessageConstant.ORDER_NOT_FOUND);
       }
        Orders byId = ordersMapper.getById(id);
       OrderVO orderVO = new OrderVO();
       BeanUtils.copyProperties(byId,orderVO);
       orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 再来一单
     * @param id
     *
     */
    @Override
    public void againOrders(Long id) {
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(id);
        if (orderDetailList == null || orderDetailList.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        for (OrderDetail orderDetail : orderDetailList) {
                   ShoppingCart shoppingCart = ShoppingCart.builder()
                          .userId(BaseContext.getCurrentId())
                          .name(orderDetail.getName())
                          .image(orderDetail.getImage())
                          .dishFlavor(orderDetail.getDishFlavor())
                          .number(orderDetail.getNumber())
                          .amount(orderDetail.getAmount())
                          .dishId(orderDetail.getDishId())
                          .setmealId(orderDetail.getSetmealId())
                          .createTime(LocalDateTime.now())
                          .build();
                  shoppingCartMapper.save(shoppingCart);
        }
    }

    /**
     * 订单分页查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        List<OrderVO> ordersList = ordersMapper.historyOrders(ordersPageQueryDTO);
        ordersList.forEach(orderVO -> {
            orderVO.setOrderDetailList(orderDetailMapper.selectByOrderId(orderVO.getId()));
            orderVO.setOrderDishes(orderVO.getOrderDetailList().stream().map(orderDetail -> orderDetail.getName() + "*" + orderDetail.getNumber()).collect(Collectors.joining(",")));
        });
        Page<OrderVO> page = (Page<OrderVO>) ordersList;
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 订单状态统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        Integer toBeConfirmed = ordersMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = ordersMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = ordersMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;


    }

    /**
     * 接单
     * @param
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Long id = ordersConfirmDTO.getId();
        ordersMapper.updateStatus(Long.valueOf(id),Orders.CONFIRMED,LocalDateTime.now(),null);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Long id = ordersRejectionDTO.getId();
        String rejectionReason = ordersRejectionDTO.getRejectionReason();
        ordersMapper.updateStatus(Long.valueOf(id),Orders.CANCELLED,LocalDateTime.now(),rejectionReason);
    }

    /**
     * 管理员取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
        Long id = ordersCancelDTO.getId();
        String cancelReason = ordersCancelDTO.getCancelReason();
        ordersMapper.updateStatus(Long.valueOf(id),Orders.CANCELLED,LocalDateTime.now(),cancelReason);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        ordersMapper.updateStatus(id,Orders.DELIVERY_IN_PROGRESS,LocalDateTime.now(),null);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        ordersMapper.updateStatus(id,Orders.COMPLETED,LocalDateTime.now(),null);
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        //为替代微信支付成功后的数据库订单状态更新，多定义一个方法进行修改

        Integer OrderPaidStatus = Orders.PAID;//支付状态，已支付

        Integer OrderStatus = Orders.TO_BE_CONFIRMED;//订单状态，待接单

//发现没有将支付时间 check_out属性赋值，所以在这里更新

        LocalDateTime check_out_time = LocalDateTime.now();
        //通过用户id，获取当前订单id
        Long id = ordersMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(), userId).getId();

        ordersMapper.updateStatuswx(OrderStatus, OrderPaidStatus, check_out_time,id);
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return vo;

}


    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);

        // 向客户端发送订单通知
        Map map = new HashMap();
        map.put("type", 1);// 1表示来单提醒 2表示客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号：" + outTradeNo);
        String jsonString = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

    /**
     * 催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        // 根据订单id查询订单
        Orders orders = ordersMapper.getById(id);
        // 判断订单状态
        if (!orders.getStatus().equals(Orders.TO_BE_CONFIRMED) || orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 向客户端发送订单通知
        Map map = new HashMap();
        map.put("type", 2);// 1表示来单提醒 2表示客户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        String jsonString = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }
}
